<template>
  <!--  表格：装主体数据   -->
  <div>
    <div class="button-container" style="text-align: left">
      <el-button type="primary" @click="addFlower">添加花卉</el-button>
    </div>
    <el-table ref="multipleTable" :data="flowerList" tooltip-effect="dark" style="width: 100%;"
              @selection-change="handleSelectionChange" line-hight="38px">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="fid" label="用户编号" width="120"></el-table-column>
      <el-table-column prop="fname" label="商品名称" width="120"></el-table-column>
      <el-table-column prop="types.tname" label="品种" width="120"></el-table-column>
      <el-table-column prop="faddress" label="产地" width="60"></el-table-column>
      <el-table-column prop="flangure" label="花语" width="120"></el-table-column>
      <el-table-column label="鲜花样例" width="120">
        <template slot-scope="scope">
          <el-avatar :size="60" :src="scope.row.fsrc"  @error="errorHandler" shape="square">
            <img src="imgs/avatar_error.png"/>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="单价" width="120"></el-table-column>
      <el-table-column prop="number" label="数量" width="120"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle
                     @click="handleEdit(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle
                     @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--  分页   -->
    <br>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNums"
        :page-sizes="[1, 2, 3]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    >
    </el-pagination>


  <!-- 修改的模态框 -->
  <el-dialog :title="title" :visible.sync="dialogFormVisible">
    <el-form :model="flower" :rules="rules" ref="sbuinessForm" label-width="120px">
      <el-form-item label="鲜花编码" prop="fid">
        <el-input v-model="flower.fid" autocomplete="off" readonly></el-input>
      </el-form-item>
      <el-form-item label="鲜花名称" prop="fname">
        <el-input v-model="flower.fname" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="鲜花产地" prop="faddress">
        <el-input v-model="flower.faddress" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="花语" prop="flangure">
        <el-input v-model="flower.flangure" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="flower.price" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="数量" prop="price">
        <el-input v-model="flower.number" autocomplete="off"></el-input>
      </el-form-item>
      <el-select v-model="flower.types.tid"  placeholder="请选择">
        <el-option
            v-for="item in typesss"
            :key="item.tid"
            :label="item.tname"
            :value="item.tid">
        </el-option>
      </el-select>
      <el-form-item label="鲜花样例" prop="src">
        <el-upload
            class="avatar-uploader"
            action="http://localhost:9092/file/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
          <img v-if="flower.fsrc" :src="flower.fsrc" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancelSubmit">取 消</el-button>
      <el-button type="primary"  @click="updateFlower">确 定</el-button>
    </div>
  </el-dialog>



    <el-dialog :title="title" :visible.sync="dialogFormVisibles">
      <el-form :model="flower" :rules="rules" ref="sbuinessForm" label-width="120px">
        <!-- ... 其他表单项 ... -->
        <el-form-item label="商铺编码" prop="shops.sid" :rules="[{ required: true, message: '商铺编码不能为空', trigger: 'blur' }]">
          <el-input v-model="flower.shops.sid" autocomplete="off" readonly></el-input>
        </el-form-item>
        <el-form-item label="鲜花名称" prop="fname" :rules="[{ required: true, message: '鲜花名称不能为空', trigger: 'blur' }]">
          <el-input v-model="flower.fname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="鲜花产地" prop="faddress" :rules="[{ required: true, message: '鲜花产地不能为空', trigger: 'blur' }]">
          <el-input v-model="flower.faddress" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="花语" prop="flangure" :rules="[{ required: true, message: '花语不能为空', trigger: 'blur' }]">
          <el-input v-model="flower.flangure" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price" :rules="[{ required: true, message: '价格不能为空', trigger: 'blur' },
                                                       { type: 'number', message: '价格必须为数字', trigger: 'blur' }]">
          <el-input v-model="flower.price" @input="flower.price = Number(flower.price)" placeholder="请输入数字" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="number" :rules="[{ required: true, message: '数量不能为空', trigger: 'blur' },
                                                       { type: 'number', message: '数量必须为数字', trigger: 'blur' }]">
          <el-input v-model="flower.number" @input="flower.number = Number(flower.number)" placeholder="请输入数字" autocomplete="off"></el-input>
        </el-form-item>
        <el-select v-model="flower.types.tid"  placeholder="请选择">
          <el-option
              v-for="item in typesss"
              :key="item.tid"
              :label="item.tname"
              :value="item.tid">
          </el-option>
        </el-select>
        <el-form-item label="鲜花样例" prop="src">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:9092/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="flower.fsrc" :src="flower.fsrc" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSubmits">取 消</el-button>
        <el-button type="primary"  @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.table-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.button-container {
  margin-bottom: 10px;
  padding-left: 0;/* 根据需要调整间距 */
}
</style>
<script>


import request from "@/utils/request";

export default {
  data() {
    return {
      total: '',
      pageNums: 1,
      pageSize: 3,
      Shop: {
        sid: 0,
        sname: '',
        spassword: '',
        siphone: '',
        src: '',
      },
      typess: {
        tid: 0,
        tname: '',
      },
      flowerList: [],
      flower: {
        fid: 0,
        fname: '',
        types: {
          tid: 0,
          tname: '',
        },
        faddress: '',
        flangure: '',
        fsrc: '',
        shops: {
          sid: 0,
          sname: '',
          spassword: '',
          siphone: '',
          src: '',
        },
        typesss: [],
        price: '',
        number: ''
      },
      title: '修改页面',
      shopsName: '',
      dialogFormVisible: false,
      dialogFormVisibles: false,
      dialogFormVisibless: false,
      rules: {
        shops: {
          sid: [
            { required: true, message: '商铺编码不能为空', trigger: 'blur' }
          ]
        },
        fname: [
          { required: true, message: '鲜花名称不能为空', trigger: 'blur' }
        ],
        faddress: [
          { required: true, message: '鲜花产地不能为空', trigger: 'blur' }
        ],
        flangure: [
          { required: true, message: '花语不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '数量不能为空', trigger: 'blur' },
          { type: 'number', message: '数量必须为数字', trigger: 'blur' }
        ]
      },
    }
  },

  methods: {
    handleSizeChange(newSize) {
      this.pageNums = 1;
      this.pageSize = newSize;
      this.initData()
    },
    handleCurrentChange(newPage) {
      this.pageNums = newPage;
      this.initData()
    },
    getToken(){
      request({
        method: 'post',
        url: 'http://localhost:9092/shops/getTook',
      }).then(res => {
        if (res.data.code === 200) {
          this.Shop = res.data.data;
          this.shopsName = res.data.data.sname
          this.Shop.sname = this.shopsName;
          this.src = res.data.data.src
          this.initData()
        }else {
          this.$router.replace("/")
        }
      })
    },
    cancelSubmit() {
      this.dialogFormVisible = false;
      this.resetUserForm();
      this.reset()
      this.initData()
    },
    reset() {
      this.flower.fname = '';
      this.flower.faddress = '';
      this.flower.flangure = '';
      this.flower.fsrc = '';
      this.flower.price = 0.0;
      this.flower.number = 0;
    },
    cancelSubmits() {
      this.dialogFormVisibles = false;
      this.resetUserForm();
      this.reset()
      this.initData()
    },
    resetUserForm() {
      this.$refs.sbuinessForm.resetFields();
    },
    handleAvatarSuccess(res) {
      this.flower.fsrc = res.data;
    },
    beforeAvatarUpload(file) {
      // 检查文件类型是否为 JPG, PNG 或 WebP
      const isJPGorPNGorWebP = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      const isLt2M = file.size / 1024 / 1024 < 2; // 检查文件大小是否小于 2MB

      if (!isJPGorPNGorWebP) {
        this.$message.error('上传头像图片只能是 JPG, PNG 或 WebP 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPGorPNGorWebP && isLt2M;
    },
    handleEdit(row) {
      this.flower = row;
      this.dialogFormVisible = true;
    },
    handleDelete(row) {
      let len = this.total;
      let sizes = this.pageSize;
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: 'http://localhost:9092/commodity/delete',
          method: 'post',
          data: row
        }).then(response => {
          if (response.data.code === 200) {
            this.$message({
              type: 'success',
              message: response.data.msg
            });
            if ((len-1)  % sizes === 0) {
              this.pageNums -= 1;
            }
            this.getToken()
          } else {
            this.$message({
              type: 'error',
              message: response.data.msg
            });
          }
        }).catch(error => {
          console.error('请求失败:', error);
          this.$message.error('请求失败');
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    initData() {
      request({
        url: 'http://localhost:9092/commodity/findAll',
        method: 'post',
        params: {
          pageNum: this.pageNums,
          pageSize: this.pageSize
        }
      }).then(response => {
        if (response.data.code === 200) {
          this.$message({
            type: 'success',
            message: response.data.msg
          });
          this.flowerList = response.data.data.data
          this.total = response.data.data.total
          console.log(response.data)
        } else {
          this.$message({
            type: 'error',
            message: response.data.msg
          });
        }
      }).catch(error => {
        console.error('请求失败:', error);
        this.$message.error('请求失败');
      });
    },
    readType(){
      request({
        method: 'post',
        url: 'http://localhost:9092/Types/findAlls',
      }).then(res => {
        if (res.data.code===200) {
          this.typesss = res.data.data;
        }
      })
    },
    updateFlower(){
      this.$confirm('此操作将永久修改该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          method: 'post',
          url: 'http://localhost:9092/commodity/updateCommodity',
          data: this.flower,
        }).then(res => {
          if (res.data.code===200) {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            this.dialogFormVisible = false;
            this.reset()
            this.getToken()
          }else {
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消修改'
        });
      });
    },
    submitForm() {
      this.$refs.sbuinessForm.validate((valid) => {
        if (valid) {
          if (valid) {
            // 在提交前转换数量为数字
            this.flower.number = Number(this.flower.number);
            this.flower.price = Number(this.flower.price)
            this.addsFlower();
          } else {
            this.$message.error('请检查表单数据');
          }
          this.addsFlower();
        } else {
          // 验证失败
          console.log('表单验证失败');
          this.$message.error('请检查表单数据');
          return false;
        }
      });
    },
    addsFlower(){
      let len = this.total;
      let sizes = this.pageSize;
      this.$confirm('此操作将永久添加该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          method: 'post',
          url: 'http://localhost:9092/commodity/addsCommodity',
          data: this.flower,
        }).then(res => {
          if (res.data.code===200) {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            this.dialogFormVisibles = false;
            this.reset()
            if (len  % sizes === 0) {
              this.pageNums += 1;
            }
            this.getToken()
          }else {
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消添加'
        });
      });
    },
    addFlower(){
      this.title = "添加页面";
      this.dialogFormVisible = false;
      this.dialogFormVisibles = true;
    },
  },
  created() {
    this.getToken()
    this.readType(this.Shop);
  }
}
</script>